package producerandconsumer;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

public class PCData3 {
    private int num = 0;
    private int size = 10;
    private Lock lock;
    private Condition producerCondition;
    private Condition consumerCondition;

    public PCData3(Lock lock,Condition producerCondition,Condition consumerCondition){
        this.lock = lock;
        this.producerCondition = producerCondition;
        this.consumerCondition = consumerCondition;
    }
    //向资源池中添加资源
    public void add(){
        lock.lock();
        try{
            if(num < size){
                num++;
                System.out.println(Thread.currentThread().getName()+"生产一件资源，当前资源池还有"+num+"个");
                consumerCondition.signalAll();
            }else{
                producerCondition.await();
                System.out.println(Thread.currentThread().getName()+"生产者线程进入等待状态");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    //从资源池中取走资源
    public void remove(){
        lock.lock();
        try {
            if(num > 0){
                num--;
                System.out.println(Thread.currentThread().getName()+"消费了一件资源，资源池中还剩"+num+"个");
                producerCondition.signalAll();
            }else{
                consumerCondition.await();
                System.out.println(Thread.currentThread().getName()+"消费者进入等待状态");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
